<template>
  <div>
    <el-container>
      <el-header>管理员后台</el-header>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="24">
            <!-- 新增站点按钮 -->
            <el-button type="success" size="small" @click="addStation">添 加 站 点</el-button>

            <!-- 站点列表 -->
            <el-table :data="stations" style="width: 100%">
              <el-table-column prop="name" label="站点名称" width="180"></el-table-column>
              <el-table-column prop="longitude" label="经度" width="180"></el-table-column>
              <el-table-column prop="latitude" label="纬度" width="180"></el-table-column>
              <el-table-column prop="card" label="营业执照图片" width="180"></el-table-column>
              <el-table-column prop="startTime" label="开门时间" width="180" format="HH:mm"></el-table-column>
              <el-table-column prop="endTime" label="关门时间" width="180" format="HH:mm"></el-table-column>
              <el-table-column prop="introduce" label="站点介绍" width="180"></el-table-column>
              <el-table-column prop="state" label="状态" width="180" :formatter="formatState"></el-table-column>
              <el-table-column prop="curatorId" label="负责人账号ID" width="180"></el-table-column>
              <el-table-column prop="curatorName" label="负责人姓名" width="180"></el-table-column>
              <el-table-column prop="curatorPhone" label="负责人电话" width="180"></el-table-column>

              <!-- 操作列 -->
              <el-table-column label="操作" width="350">
                <template #default="scope">
                  <el-button type="success" size="small" @click="changeState(scope.row)">更改站点状态</el-button>
                  <el-button type="success" size="small" @click="changeHandler(scope.row)">更换负责人</el-button>
                  <el-button v-show="scope.row.state==1" type="danger" size="small" @click="readyDel(scope.row)">删除站点</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-main>

      <!-- 新增站点对话框 -->
      <el-dialog v-loading="loading" title="新增站点数据" :visible.sync="showAddWindow" width="80%" @open="onDialogOpen">
        <el-form :model="newStation" label-width="120px">
          <el-form-item label="站点名称">
            <el-input v-model="newStation.name"></el-input>
          </el-form-item>
          <el-form-item label="经度">
            <el-input v-model="newStation.longitude" disabled></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input v-model="newStation.latitude" disabled></el-input>
          </el-form-item>
          <el-form-item label="开门时间">
            <el-time-picker v-model="newStation.startTime" placeholder="选择开门时间" format="HH:mm"></el-time-picker>
          </el-form-item>
          <el-form-item label="关门时间">
            <el-time-picker v-model="newStation.endTime" placeholder="选择关门时间" format="HH:mm"></el-time-picker>
          </el-form-item>
          <el-form-item label="站点介绍">
            <el-input v-model="newStation.introduce"></el-input>
          </el-form-item>
          <el-form-item label="请选择负责人">
            <el-select v-model="choosenHandler" placeholder="请选择" @change="showNew">
              <el-option v-for="item in useFulHandler" :key="item.accountId" :label="item.employeName" :value="item.accountId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择位置">
            <el-button @click="showLocation">点击选择位置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="addNow">执行新增</el-button>
        <el-button @click="showAddWindow = false" type="danger" round>关 闭</el-button>
      </el-dialog>

      <!-- 地图选择位置 -->
      <div v-show="showMap">
        <div id="container" style="width: 100%; height: 400px;"></div>
        <el-button type="primary" @click="confirmLocation">确认选择</el-button>
        <el-button @click="showMap = false" type="danger" round>关 闭</el-button>
      </div>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNum"
        :page-sizes="[3, 4, 5]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
      </el-pagination>
    </el-container>

    <!-- 更换负责人对话框 -->
    <el-dialog v-loading="loading" title="更换站点负责人" :visible.sync="showChangeWindow" width="80%" >
      <el-form :model="newHandler" label-width="120px">
        <el-form-item label="请选择新的负责人">
          <el-select v-model="newHandlerId" placeholder="请选择" @change="showChange">
            <el-option v-for="item in usefulHandlerEx" :key="item.accountId" :label="item.employeName" :value="item.accountId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="changeHandlerNow">立即修改</el-button>
      <el-button @click="showChangeWindow = false" type="danger" round>关 闭</el-button>
    </el-dialog>

    <!-- 删除站点对话框 -->
    <el-dialog v-loading="loading" title="删除站点" :visible.sync="showDelWindow" width="80%" >
        <div style="margin-bottom: 20px;">
          确认要删除吗？此操作不可逆。
        </div>
      <el-button type="primary" @click="del()">立即删除</el-button>
      <el-button @click="showDelWindow = false" type="danger" round>关 闭</el-button>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Admin",
    data() {
      return {
        selectRow: null, // 选中的行
        showDelWindow: false, // 显示删除窗口
        stationId: 0, // 站点ID
        newHandlerId: null, // 新的负责人ID
        usefulHandlerEx: [], // 可用负责人列表（排除当前负责人）
        newHandler: null, // 新的负责人信息
        showChangeWindow: false, // 显示更换负责人窗口
        choosenHandler: null, // 选中的负责人
        showMap: false, // 显示地图
        showAddWindow: false, // 显示新增站点窗口
        loading: false, // 加载状态
        stations: [], // 站点列表
        newStation: { // 新增站点表单数据
          name: "",
          longitude: "",
          latitude: "",
          card: "",
          startTime: "",
          endTime: "",
          introduce: ""
        },
        useFulHandler: [], // 可用负责人列表
        page: { // 分页数据
          pageNum: 1,
          pageSize: 5,
          total: 0
        },
        map: null, // 地图对象
        marker: null // 地图标记
      };
    },
    mounted() {
      this.loadAllStations(this.page.pageNum, this.page.pageSize);
    },
    methods: {
      // 准备删除站点
      readyDel(row) {
        this.showDelWindow = true;
        this.selectRow = row;
      },
      // 更改站点状态
      changeState(row) {
        this.$http.get("/station/station/changeState/" + row.id).then(resp => {
          if (resp.data.code == 200) {
            this.$message.success("修改成功!");
            this.loadAllStations(this.page.pageNum, this.page.pageSize);
          } else {
            this.$message.error("修改失败: " + resp.data.message);
          }
        });
      },
      // 删除站点
      del() {
        this.showDelWindow = true;
        this.$http.get("/station/station/del/" + this.selectRow.id).then(resp => {
          if (resp.data.code == 200) {
            this.$message.success("删除成功!");
            this.loadAllStations(this.page.pageNum, this.page.pageSize);
          } else {
            this.$message.error("删除失败: " + resp.data.message);
          }
        });
      },
      // 更换负责人时显示新的负责人
      showChange() {
        console.log("新的负责人:", this.newHandlerId);
      },
      // 立即更换负责人
      changeHandlerNow() {
        this.showChangeWindow = false;
        this.$http.get("/station/station/changeHandler/" + this.newHandlerId + "/" + this.stationId).then(resp => {
          if (resp.data.code == 200) {
            this.$message.success("更改成功");
            this.loadAllStations(this.page.pageNum, this.page.pageSize);
          } else {
            this.$message.error("更改失败: " + resp.data.message);
          }
        });
      },
      // 格式化状态
      formatState(row) {
        switch (row.state) {
          case 0:
            return "正常";
          case 1:
            return "暂停营业";
          case 2:
            return "删除";
          default:
            return "未知";
        }
      },
      // 处理分页大小变化
      handleSizeChange(pageSize) {
        this.page.pageSize = pageSize;
        this.loadAllStations(this.page.pageNum, this.page.pageSize);
      },
      // 处理当前页变化
      handleCurrentChange(pageNum) {
        this.page.pageNum = pageNum;
        this.loadAllStations(this.page.pageNum, this.page.pageSize);
      },
      // 显示地图选择位置
      showLocation() {
        this.showMap = true;
        this.showAddWindow = false;
      },
      // 新增站点对话框打开时初始化地图
      onDialogOpen() {
        if (!this.map) {
          setTimeout(() => {
            this.initMap();
          });
        }
      },
      // 初始化地图
      initMap() {
        console.log("Initializing map...");
        this.map = new AMap.Map("container", {
          resizeEnable: true,
          zoom: 10,
          center: [116.397428, 39.90923], // 初始化地图中心点
        });
        this.map.on("click", this.onMapClick);
        console.log("Map initialized.");
      },
      // 地图点击事件
      onMapClick(e) {
        this.newStation.longitude = e.lnglat.getLng();
        this.newStation.latitude = e.lnglat.getLat();
        if (this.marker) {
          this.marker.setPosition(e.lnglat);
        } else {
          this.marker = new AMap.Marker({
            position: e.lnglat,
            map: this.map,
          });
        }
      },
      // 显示可用负责人，排除当前负责人
      showUsefulHandlerExceptOne(id) {
        console.log(id);
        this.$http.get("/staff/employee/showUsefulHandlerExceptOne/" + id).then(resp => {
          console.log(resp.data.data);
          this.usefulHandlerEx = resp.data.data;
        });
      },
      // 显示新增站点窗口
      addStation() {
        this.showUsefulHandler();
        this.showAddWindow = true;
      },
      // 显示所有可用负责人
      showUsefulHandler() {
        this.$http.get("/staff/employee/findUsefulHandler").then(resp => {
          this.useFulHandler = resp.data.data;
        });
      },
      // 显示新负责人
      showNew() {
        console.log("选中的负责人:", this.choosenHandler);
      },
      // 执行新增站点
      addNow() {
        this.newStation.curatorId = this.choosenHandler;
        this.$http.post("/station/station/add", this.newStation).then(resp => {
          if (resp.data.code == 200) {
            this.$message.success("站点新增成功");
            this.showAddWindow = false;
            this.loadAllStations(this.page.pageNum, this.page.pageSize);
          } else {
            this.$message.error("站点新增失败: " + resp.data.message);
          }
        });
      },
      // 加载所有站点
      loadAllStations(pageNum, pageSize) {
        this.$http.get("/station/station/loadAll", {
          params: {
            pageNum: pageNum,
            pageSize: pageSize
          }
        }).then(response => {
          console.log(response.data.data);
          const result = response.data.data;
          this.page.pageNum = result.current;
          this.page.pageSize = result.size;
          this.page.total = result.total;
          this.stations = result.records;
        }).catch(error => {
          console.error("Error fetching stations:", error);
        });
      },
      // 更换负责人
      changeHandler(row) {
        this.showUsefulHandlerExceptOne(row.curatorId);
        this.stationId = row.id;
        this.showChangeWindow = true;
        console.log("更换负责人:", row);
      },
      // 确认选择位置
      confirmLocation() {
        this.showMap = false;
        this.showAddWindow = true;
        this.$message.success("位置选择成功");
      },
    },
  };
</script>


<style scoped>

</style>
